package com.panda.web.utils;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

public class WechatHttpClientBuilder {
    
    public static CloseableHttpClient createSecuredClient(String certPath, String password) {
        try {
            // 加载证书
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new FileInputStream(certPath), password.toCharArray());
            
            // 创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            
            // 初始化KeyManager
            KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmFactory.init(keyStore, password.toCharArray());
            
            // 使用信任所有策略（微信支付不需要验证服务器证书）
            TrustStrategy trustStrategy = (x509Certificates, s) -> true;
            TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmFactory.init((KeyStore) null);
            
            sslContext.init(kmFactory.getKeyManagers(), tmFactory.getTrustManagers(), new SecureRandom());
            
            // 创建SSL Socket Factory
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                new String[]{"TLSv1.2"},
                null,
                (hostname, session) -> true // 信任所有主机名
            );
            
            // 创建HTTP客户端
            return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
        } catch (Exception e) {
            throw new RuntimeException("创建安全HTTP客户端失败", e);
        }
    }
}